package com.doublethread.easymart.modules.product.controller;

import com.doublethread.easymart.common.result.PageResult;
import com.doublethread.easymart.common.result.Result;
import com.doublethread.easymart.modules.product.dto.ProductQueryDTO;
import com.doublethread.easymart.modules.product.service.CategoryService;
import com.doublethread.easymart.modules.product.service.ProductService;
import com.doublethread.easymart.modules.product.vo.CategoryVO;
import com.doublethread.easymart.modules.product.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 分类控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/public/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    /**
     * 获取分类树
     */
    @GetMapping("/tree")
    public Result<List<CategoryVO>> getCategoryTree() {
        log.info("获取分类树");

        List<CategoryVO> categoryTree = categoryService.getCategoryTree();

        log.info("获取分类树成功");
        return Result.success(categoryTree);
    }

    /**
     * 获取一级分类列表
     */
    @GetMapping("/first-level")
    public Result<List<CategoryVO>> getFirstLevelCategories() {
        log.info("获取一级分类列表");

        List<CategoryVO> categories = categoryService.getFirstLevelCategories();

        log.info("获取一级分类列表成功");
        return Result.success(categories);
    }

    /**
     * 获取子分类列表
     */
    @GetMapping("/{parentId}/children")
    public Result<List<CategoryVO>> getSubCategories(@PathVariable Long parentId) {
        log.info("获取子分类列表");

        List<CategoryVO> subCategories = categoryService.getSubCategories(parentId);

        log.info("获取子分类列表成功");
        return Result.success(subCategories);
    }

    /**
     * 获取分类商品列表
     */
    @GetMapping("/{categoryId}/products")
    public Result<PageResult<ProductVO>> getProductsByCategory(
            @PathVariable Long categoryId,
            ProductQueryDTO queryDTO) {
        log.info("获取分类商品");

        // 设置分类ID到查询条件中
        queryDTO.setCategoryId(categoryId);

        // 复用商品服务的查询逻辑
        PageResult<ProductVO> pageResult = productService.getProductList(queryDTO);

        log.info("获取分类商品成功");

        return Result.success(pageResult);
    }
}
